<template>
	<view class="schedule-list">
		<view class="title">
			<view>进度列表</view>
			<image @click="goFilterPage" src="../../../../../subpackage-overhaul/static/icon-style-7.png"></image>
		</view>
		
		<scroll-view v-if="scheduleList.length" @scrolltolower="scrolltolower" scroll-y style="max-height: 500px;">
			<view @click="goScheduleDetails(item)" v-for="(item, index) in scheduleList" :key="index" class="schedule-item">
				<view class="item-top">
					<view class="text-tailor">{{ item.lineName || '' }}{{ item.branchLineName ? `（${item.branchLineName}）` : '' }}/{{ item.lineSiteSectionName || '' }}</view>
					<u-icon name="arrow-right" color="#a7aebd" size="20"></u-icon>
				</view>
				<view class="item-bottom">
					<view class="label" :class="[['钢环', '大钢环'].includes(item.constructionMethodStr) ? 'blue-label' : ['隧内微扰动', '隧外微扰动'].includes(item.constructionMethodStr) ? 'orange-label' : 'green-label']">
						{{ item.constructionMethodStr }}
					</view>
					<view class="date-text">{{ item.constructionDate }}</view>
				</view>
			</view>
		</scroll-view>
		<view v-if="!scheduleList.length" style="padding-bottom: 40px; min-height: 300px;">
			<u-empty mode="data" icon="http://cdn.uviewui.com/uview/empty/data.png"></u-empty>
		</view>
	</view>
</template>

<script>
	import { handleFormatDate } from '@/utils/date.js'
	import { getListByLineSiteSectionId } from "@/api/comprehensive/comprehensive.js"
	import fileMixin from "@/mixins/file.js"
	
	export default {
		mixins: [fileMixin],
		inject: ['getLineArray', 'getId'],
		data() {
			return {
				// 进度列表
				scheduleList: [],
				/** 分页器对象 */
				paging: {
					pageNum: 1,
					pageSize: 15,
					total: 0
				},
			}
		},
		methods: {
			/** 初始化 */
			init() {
				if (uni.getStorageSync("_temp_params")) {
					this.recordSearchForm = uni.getStorageSync("_temp_params")
					const { stateDate, endDate, lineId, lineSiteSectionId, lineSiteSectionType, construction } = this.recordSearchForm
					let constructionDates = []
					if (stateDate && endDate) {
						constructionDates = [
							new Date(`${handleFormatDate(new Date(stateDate))} 00:00:00`).getTime(),
							new Date(`${handleFormatDate(new Date(endDate))} 23:59:59`).getTime()
						]
					}
					this.searchForm = {
						constructionDates: constructionDates.length ? constructionDates : undefined,
						lineId: lineId ? lineId : undefined,
						lineSiteSectionId: lineSiteSectionId ? lineSiteSectionId : undefined,
						lineSiteSectionType: lineSiteSectionType ? lineSiteSectionType : undefined,
						constructionMethod: construction ? construction : undefined,
					}
					uni.removeStorageSync("_temp_params")
				}
				this.paging.pageNum = 1
				this.scheduleList = []
				this.getScheduleList()
			},
			
			/** 获取进度列表 */
			getScheduleList(params) {
				return new Promise(resolve => {
					if (!this.getId() || !this.$store.getters.dictMap || !this.$store.getters.dictMap.construction_method) {
						return
					}
					const { pageNum, pageSize } = this.paging
					getListByLineSiteSectionId({
						currPage: pageNum,
						pageSize,
						params: {
							pmId: this.getId(),
							reviewStatus: 'tg',
							projectId: uni.getStorageSync("isOwner") || undefined,
							...this.searchForm,
						},
						...(params || {})
					}).then(res => {
						if (res && res.result && Array.isArray(res.result.list)) {
							const constructionMethodList = this.$store.getters.dictMap.construction_method
							const tempArray = res.result.list.map(item => {
								const codeArray = item.constructionMethod.split(',')
								const constructionMethodStr = constructionMethodList.find(item1 => codeArray.find(item2 => item1.code === item2))
								const children = this.mergeWorkloadList(item.pmprWorkloads || [], codeArray)
								return {
									...item,
									constructionDate: item.constructionDate ? handleFormatDate(new Date(item.constructionDate)) : '',
									constructionMethodStr: constructionMethodStr ? constructionMethodStr.name : '',
									children: children.length ? children : [{}]
								}
							})
							if (!params) {
								this.paging.total = res.result.total
								this.scheduleList = this.scheduleList.concat(tempArray)
							} else {
								resolve(tempArray)
								return
							}
						}
						resolve([])
					}).catch(() => {
						resolve([])
					})
				})
			},
			
			/** 滚动到底部时触发 */
			scrolltolower() {
				if (this.paging.pageNum * this.paging.pageSize >= this.paging.total) {
					return
				}
				this.paging.pageNum++
				this.getScheduleList()
			},
			
			/** 跳转筛选页面 */
			goFilterPage() {
				if (this.recordSearchForm) {
					uni.setStorageSync("_temp_params", this.recordSearchForm)
				}
				uni.navigateTo({ url: `/subpackage-overhaul/pages/comprehensiveOverhaul/projectKanBan/filterForm?id=${this.getId()}` })
			},
			
			/** 跳转进度详情 */
			async goScheduleDetails(item) {
				if (this.loading) {
					return
				}
				this.loading = true
				const data = {
					totalWorkload: 0,
					extraWorkload: 0,
					pmprWorkloads: [],
					materialExpendList: [],
					pmprManagePersonNamesStr: '',
					laborNum: '',
					constructionMethodStr: '',
					type: ['gh', 'xgh'].includes(item.constructionMethod) ? 1 : ['snwrd', 'swwrd'].includes(item.constructionMethod) ? 2 : 3
				}
				// 处理工作量
				if (Array.isArray(item.children)) {
					let pmprWorkloads = item.children
					if (data.type === 1) {
						const resultArray = (await Promise.all(pmprWorkloads.filter(item1 => item1.docIds.length).map(item1 => item1.docIds.map(item2 => this.getFileListByDocId(item2))).flat())).flat()
						for (let i = 0; i < pmprWorkloads.length; i++) {
							pmprWorkloads[i].imageList = []
							pmprWorkloads[i].ringNumber = [...new Set(pmprWorkloads[i].ringNumber.split("、"))].join("、")
							for (let j = 0; j < pmprWorkloads[i].docIds.length; j++) {
								for (const item1 of resultArray) {
									if (item1.docInfoId === pmprWorkloads[i].docIds[j]) {
										pmprWorkloads[i].imageList.push(item1)
									}
								}
							}
						}
					}
					else {
						// 设置图片
						pmprWorkloads = item.pmprWorkloads
						const resultArray = (await Promise.all(pmprWorkloads.map(item1 => this.getFileListByDocId(item1.docId)))).flat()
						for (let i = 0; i < pmprWorkloads.length; i++) {
							for (const item1 of resultArray) {
								pmprWorkloads[i].imageList = []
								if (item1.docInfoId === pmprWorkloads[i].docId) {
									pmprWorkloads[i].imageList.push(item1)
								}
							}
						}
					}
					data.pmprWorkloads = pmprWorkloads
				}
				// 处理材料
				if (Array.isArray(item.totalMaterialList)) {
					const tempArray = []
					for (const item1 of item.totalMaterialList) {
						const index = tempArray.findIndex(item2 => item2.parentTypeName === item1.parentTypeName && item2.deviceTypeName === item1.deviceTypeName && item2.specificationModel === item1.specificationModel)
						if (index !== -1) {
							tempArray[index].num += item1.num
						} else {
							tempArray.push(item1)
						}
					}
					data.materialExpendList = tempArray.map(item1 => ({ ...item1, num: Math.round(item1.num * 100) / 100 }))
				}
				// 处理其他
				data.pmprManagePersonNamesStr = item.pmprManagePersonNames.filter(item1 => item1).join('、') || '' 
				data.laborNum = item.laborNum
				data.constructionMethodStr = item.constructionMethodStr
				uni.setStorageSync("_temp_schedule-details", data)
				uni.navigateTo({ url: `/subpackage-overhaul/pages/comprehensiveOverhaul/projectKanBan/scheduleDetails?id=${item.id}` })
				this.loading = false
			},
			
			/**
			 * 合并重复工作量
			 * @param workloadList {Array<any>} 工作量列表
			 * @param codeArray {Array<any>} 工法列表
			 * */
			mergeWorkloadList(workloadList = [], codeArray = []) {
			    const tempArray = []
			    for (const item of workloadList) {
			        let index = tempArray.findIndex(item1 => item1.steelRingProcedureName === item.steelRingProcedureName)
					const ringNumber = item.ringNumber
			        if (index === -1) {
			            tempArray.push({
			                ...item,
							ringNumber: '',
			                totalWorkload: 0,
			                extraWorkload: 0,
			                outputValue: 0,
							docIds: []
			            })
			            index = tempArray.length - 1
			        }
			        // 如果是小钢环
			        if (codeArray.includes('xgh')) {
			            const nums = item.ringNumber.split('-')
			            if (Number(nums[1]) === 2) {
			                tempArray[index].extraWorkload += 0.5
			            } else {
			                tempArray[index].totalWorkload += 0.5
			            }
			            tempArray[index].outputValue += item.price / 2
			        } else if (codeArray.includes('gh') || codeArray.includes('snwrd') || codeArray.includes('swwrd')) {
			            // 大钢环、隧内、隧外微扰动
			            tempArray[index].totalWorkload += 1
			            tempArray[index].outputValue += item.price
			        } else {
			            // 其他类型
			            tempArray[index].totalWorkload += item.workload
			            tempArray[index].outputValue += item.workload * item.price
			        }
					tempArray[index].ringNumber += !tempArray[index].ringNumber ? `${item.ringNumber}` : `、${item.ringNumber}`
					if (item.docId) {
						tempArray[index].docIds.push(item.docId)
					}
			    }
			    return tempArray.map(item => ({
			        ...item,
			        outputValue: Math.round(item.outputValue * 100) / 100,
					docIds: [...new Set(item.docIds)]
			    }))
			}
		}
	}
</script>

<style scoped lang="scss">
	.schedule-list {
		background: #fff;
		.title {
			padding: 24px 16px 15px;
			line-height: 28px;
			font-size: 20px;
			font-weight: bold;
			color: #22204e;
			display: flex;
			align-items: center;
			justify-content: space-between;
			image {
				width: 26px;
				height: 26px;
			}
		}
		.schedule-item {
			padding: 15px 0;
			margin: 0 17px;
			border-bottom: 2px dotted #f5f7fa;
			.item-top {
				display: flex;
				align-items: center;
				justify-content: space-between;
				height: 22px;
				line-height: 22px;
				color: #445469;
				font-size: 16px;
				font-weight: bold;
				.text-tailor {
					white-space: nowrap;
					text-overflow: ellipsis;
					overflow: hidden;
					max-width: 85%;
				}
			}
			.item-bottom {
				height: 30px;
				display: flex;
				align-items: center;
				justify-content: space-between;
				margin-top: 15px;
				.label {
					color: #fff;
					padding: 4px 13px;
					border-radius: 20px;
					&.blue-label {
						background: #3fcbfc;
					}
					&.orange-label {
						background: #fbb16c;
					}
					&.green-label {
						background: #15d7b0;
					}
				}
				.date-text {
					color: #919ba8;
					font-size: 16px;
					font-weight: bold;
				}
			}
		}
	}
</style>
